import {Link, useNavigate, useParams} from "react-router-dom";
import { useContext, useEffect, useState } from "react";
import { UserContext } from "../context/userContext";
import axios from "axios";
import dayjs from "dayjs";
import {Avatar, Button, Form, Input, List, Space} from "antd-mobile";

const UserInfo = () => {
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError] = useState('');

  const navigate = useNavigate();
  const {token} = useParams();

  const cancel = () => {
    navigate(-1);
  }
  useEffect(() => {
    if (!token) {
      navigate('/login');
    }
  }, [token, navigate]);

  const updateUserDetails = async (e) => {
    e.preventDefault();

    try {
      const userData = { password, confirmPassword };

      const response = await axios.patch(
        `${process.env.REACT_APP_BASE_URL}/users/reset-user`,
        userData,
        { withCredentials: true, headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.status === 201) {
        navigate("/finish");
      }
      else{console.log("修改失败")}
    } catch (error) {
      setError(error.response.data.message);
    }
  };

  return <section className="profile">
    <Form
        layout='horizontal'
        footer={
      <Space block direction="horizontal" justify='around'  wrap >
          <Button onClick={cancel} style={{'--background-color': 'rgba(80, 62, 157, 0.1)', '--text-color':'rgba(80, 62, 157, 1)', '--border-style':'none', 'width':'120px'}} block type='cancel' color='primary' size='large'>
            取消
          </Button>
          <Button onClick={updateUserDetails} style={{'--background-color': 'rgba(80, 62, 157, 1)', '--text-color':'white', '--border-style':'none', 'width':'190px'}} block type='submit' color='primary' size='large'>
            保存
          </Button>
      </Space>
        }
    >
      <Form.Header>修改密码</Form.Header>
      <Form.Item
          name='password'
          label='新密码'
          childElementPosition='right'
      >
        <Input onChange={val => setPassword(val)} placeholder='请设置新密码'/>
      </Form.Item>
      <Form.Item
          name='confirmPassword'
          label='密码重复'
          childElementPosition='right'
      >
        <Input onChange={val => setConfirmPassword(val)} placeholder='请重复输入您设置的新密码'/>
      </Form.Item>
    </Form>

  </section>;
};

export default UserInfo;


